package com.yc.meeting_attendance;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.yc.utilslib.reader.Licence;
import com.yc.utilslib.reader.Reader;
import com.yc.utilslib.reader.card.UserCard;
import com.yc.utilslib.reader.protocol.Cmd;
import com.yc.utilslib.reader.protocol.Command;
import com.yc.utilslib.reader.protocol.tagvalue.FTag;
import com.yc.utilslib.reader.protocol.tagvalue.Field;
import com.yc.utilslib.utils.DateUtils;
import com.yc.utilslib.utils.EncryptUtils;
import com.yc.utilslib.utils.GZipUtils;
import com.yc.utilslib.utils.StringUtils;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * 项目名：智慧课牌
 * Created by ${LiuShaoQing} on 2017/10/23.
 * Time: 2017/10/23 15:05
 */

public class TestMyActivity extends Activity {

    String licence;

    Reader mReader;
    TextView mTextViewShow;
    private Queue<String> mMsgQueue = new LinkedList<>();

    private Handler mUIHandler = new Handler(){

        Date lastDate = new Date(System.currentTimeMillis());
        long lastCard = 0;

        @Override
        public void handleMessage(Message msg) {
            Command cmd = (Command)msg.obj;

            switch (cmd.getCmd()) {
                case SET_TIME:
                    break;
                case GET_TIME:
                    break;
                case SET_PARA:
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    break;
                case GET_PARA:
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    break;
                case FIND_CARD:
                    break;
                case ANTI:
                    break;
                case SELECT:
                    break;
                case AUTHENTICATION:
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    break;
                case BLOCK_READ:
                    break;
                case BLOCK_WRITE:
                    break;
                case SECTOR_READ:
                    break;
                case SECTOR_WRITE:
                    break;
                case HALT:
                    break;
                case READ_CARD:
                    ShowMsg(FTag.CARD_PARA_SERIAL_NO, cmd);
                    break;
                case CONSUME:
                    break;
                case SEND_CARD_ID:
                    ShowMsg(FTag.CARD_PARA_ID, cmd);
                    break;
                case SEND_CARD_INFO:
                    Date curDate = new Date(System.currentTimeMillis());
                    long time = curDate.getTime() - lastDate.getTime();
                    long curCard = lastCard;
                    UserCard card = null;
                    if (cmd.getFieldArray().containsKey(FTag.CARD_PARA_ID)) {
                        curCard = (long)cmd.getFieldArray().get(FTag.CARD_PARA_ID).getValue();
                        card = UserCard.getInstance(cmd.getFieldArray().get(FTag.CARD_PARA_ID).getBytes(),
                                new byte[16], new byte[16], new byte[16]);
                    }

                    if (time > 2000 || lastCard != curCard) {
                    mMsgQueue.add("----------------------------------------------------");
                    ShowMsg(FTag.SYS_CMD_RET, cmd);
                    ShowMsg(FTag.CARD_PARA_ID, cmd);
                    ShowMsg(FTag.CARD_PARA_SERIAL_NO, cmd);
                    ShowMsg(FTag.CARD_PARA_TYPE, cmd);
                    ShowMsg(FTag.CARD_PARA_EXCESS_KEY, cmd);
                    ShowMsg(FTag.CARD_PARA_STOP_DATE, cmd);
                    ShowMsg(FTag.CARD_PARA_REST_MONEY, cmd);
                    ShowMsg(FTag.CARD_PARA_USED_MONEY, cmd);
                    ShowMsg(FTag.CARD_PARA_CONSUME_TIME, cmd);
                    ShowMsg(FTag.CARD_PARA_TOTAL_USED_TIMES, cmd);
                    ShowMsg(FTag.CARD_PARA_TOTAL_USED_MONEY, cmd);
                    ShowMsg(FTag.CARD_PARA_NAME, cmd);

                    if (cmd.getFieldArray().containsKey(FTag.CARD_PARA_NAME)) {
                        card.setExtendedInfo((byte[])cmd.getFieldArray().get(FTag.CARD_PARA_NAME).getValue());

                        mMsgQueue.add("EmpName:" + card.getExtendedInfo().getEmployeeName());
                        mMsgQueue.add("EmpStrID:" + card.getExtendedInfo().getEmployeeStrId());
                        mMsgQueue.add("CardType:" + card.getExtendedInfo().getCardType());
                    }

                    lastDate = curDate;
                    lastCard = curCard;
                    }
                    break;
            }

            int index = mMsgQueue.size();
            mTextViewShow.setText(null);
            for (int i = index; i > 0 ; i--) {
                String value = mMsgQueue.poll();
                mTextViewShow.append(value + "\r\n");
                if (i < 20) {
                    mMsgQueue.add(value);
                }
            }
        }

        private void ShowMsg(FTag tag, Command cmd) {
            if (cmd.getFieldArray().containsKey(tag)) {
                mMsgQueue.add(DateUtils.YYYYMMDDHHMMSS_SHORT.format(new Date(System.currentTimeMillis())) + " : " +
                        cmd.getCmd().getName() + " | " +
                        cmd.getFieldArray().get(tag).toString());
            }
        }
    };

    private Handler mReaderErrorHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            mReader.restart();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_test_main);

        mTextViewShow = (TextView) findViewById(R.id.sample_text);

        mReader = new Reader("/dev/ttyS3", 115200);
        mReader.setmHandlerError(mReaderErrorHandler);
        if (!mReader.open(mUIHandler)) {
            mTextViewShow.setText("读卡器打开失败！！！");
        } else {
            SharedPreferences sp = getSharedPreferences("Consumer",
                    Context.MODE_PRIVATE);
            licence = sp.getString("licence", StringUtils.EMPTY);

            //由于测试设备无法联网，只能指定lic的值
            if (StringUtils.isNullOrEmpty(licence)) {
                licence = "H4sIAAAAAAAACwGAAH//l5t20s5NefgiFEh0YvA0/0BH7GbOvxRhYSxUeJYyJ8gtN5p5IAc00IAYrziMjpiiVmZcwMeFPPJHb9VkQhlg6MDu1Tdl7i2ZqsBPdz+mHpsAXVo7xFARqUbKkuizUDCnPyyPAEbLb9p+SsYTg/SVUj7wzsxUPf2IHa6OuqPWWugCv3q2gAAAAA==";
            }

            if (StringUtils.isNullOrEmpty(licence)) {
               /* //没有找到保存的lic数据，需要从接口中加载
                IService<String, String> mQueryLicenceService = new QueryLicenceService();
                mQueryLicenceService.setOnRequestResultListener(
                        new IService.OnServiceResultListener<String, String>() {
                            @Override
                            public void onResult(String key, String lic) {
                                if (!StringUtils.isNullOrEmpty(lic) && loadLicence(lic)) {

                                } else {
                                    Toast.makeText(MainActivity.this, R.string.api_error_request_fail
                                            , Toast.LENGTH_SHORT).show();
                                    MainActivity.this.finish();
                                }
                            }
                        }
                );
                mQueryLicenceService.setOnServiceErrorListener(
                        new IService.OnServiceErrorListener<String>() {
                            @Override
                            public void onError(String request, String message) {
                                Toast.makeText(MainActivity.this, message
                                        , Toast.LENGTH_SHORT).show();
                                Handler handler = new Handler();
                                //当计时结束,跳转至设置界面
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        MainActivity.this.finish();
                                    }
                                }, 1000);
                            }
                        }
                );
                mQueryLicenceService.query("123");
*/
                //如果没有设置接口地址或从接口中加载失败，则跳转到接口配置界面，直到接口配置成功才允许继续使用

            } else {
                if (loadLicence(licence)) {
                    Map<FTag, Field> para = new HashMap<>();
                    para.put(FTag.SYS_WORK_MODE,
                            Field.getInstance(FTag.SYS_WORK_MODE, 0x00));
                    para.put(FTag.SYS_COMM_MODE,
                            Field.getInstance(FTag.SYS_COMM_MODE, 0x00));
                    para.put(FTag.SYS_PARA_XF_SECTOR,
                            Field.getInstance(FTag.SYS_PARA_XF_SECTOR, Licence.getInstance().getXfxt_sec()));
                    para.put(FTag.SYS_PARA_SK_SECTOR,
                            Field.getInstance(FTag.SYS_PARA_SK_SECTOR, Licence.getInstance().getJsxt_sec()));
                    para.put(FTag.SYS_READ_MODE,
                            Field.getInstance(FTag.SYS_READ_MODE, 1));
                    para.put(FTag.CARD_PARA_AUTH_TYPE,
                            Field.getInstance(FTag.CARD_PARA_AUTH_TYPE, 0x60));
                    para.put(FTag.SYS_PARA_KEY_A,
                            Field.getInstance(FTag.SYS_PARA_KEY_A, Licence.getInstance().getOprater_password()));
                    para.put(FTag.SYS_PARA_KEY_B,
                            Field.getInstance(FTag.SYS_PARA_KEY_B, Licence.getInstance().getKeyB()));
                    para.put(FTag.SYS_MACHINE_NO,
                            Field.getInstance(FTag.SYS_MACHINE_NO, 0x0001));
                    Command auth = new Command(Cmd.SET_PARA, para);
                    mReader.SetCommand(auth);
                } else {
                   /* Toast.makeText(TestMyActivity.this, R.string.app_load_error_licence
                            , Toast.LENGTH_SHORT).show();*/
                }
            }
        }
    }

    /**
     * 加载Lic信息
     *
     * @param licence Lic数据
     * @return 是否成功
     */
    private boolean loadLicence(String licence) {
        byte[] decData = GZipUtils.decompressForGzip(licence);
        Licence.fromData(EncryptUtils.AES.decrypt(decData,
                "y&c@sz^%,.r#T*!~".getBytes(Charset.forName("ASCII"))));

        return Licence.getInstance().getXfxt_sec() > 0;
    }

}
